#!/usr/bin/env python3

import pandas as pd
#下面这个包是调用计算欧几里得距离的
from sklearn.metrics.pairwise import euclidean_distances
#引入Kmeans算法
from sklearn.cluster import KMeans

if __name__ == '__main__':
    votes = pd.read_csv("114_congress.csv")
    #打印party这一列的属性个数
    votes_party = votes["party"].value_counts()
    # print(votes_party)
    #计算平均每个条款的平均值
    state_mean = votes.mean()
    # print(state_mean)
    #计算第0行和第1行的数据的欧氏距离
    demo_distance = euclidean_distances(votes.iloc[0,3:].values.reshape((1,-1)),votes.iloc[1,3:].values.reshape((1,-1)))
    # print(demo_distance)
    #设置KMeans参数
    kmeans_model = KMeans(n_clusters = 2,random_state = 1)
    #给KMeans带入数据
    senator_distances = kmeans_model.fit_transform(votes.iloc[:,3:])
    # print(senator_distances)

    #得出距离哪个簇最近，划分好标签（0或1）
    labels = kmeans_model.labels_
    # print(labels)
    #找出其中三个异常的人（为什么是三个是因为下面的代码可以看出来）
    democratic_outliers = votes[(labels == 1) & (votes["party"] == "D")]
    # print(democratic_outliers)
    #将数据中的党派属性打印出来
    labels = pd.crosstab(labels,votes["party"])
    # print(labels)
    #将每列的所有数据求三次方然后求和，并添加到一个新的extremism列中
    extremism = (senator_distances ** 3).sum(axis = 1)
    votes["extremism"] = extremism
    #按照降序排序
    votes.sort_values("extremism",inplace = True,ascending = False)
    print(votes.head(10))
